﻿#ifndef SERIALMANAGER_H
#define SERIALMANAGER_H

#include <QObject>
#include <QSerialPort>
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <QQueue>
#include <qtimer.h>

//串口相关参数的设置
struct portSettings
{
    QString portName;
    QSerialPort::BaudRate boudRate;
    QSerialPort::DataBits dataBits;
    QSerialPort::StopBits stopBoits;
    QSerialPort::Parity   parity;
    int responseTime;
};

Q_DECLARE_METATYPE(portSettings)


class serialManager : public QObject
{
    Q_OBJECT


public:
    explicit serialManager(QObject* parent = nullptr);
    ~serialManager();

public slots:
    void openSerialPort(const portSettings& portSeting);//打开串口
    void stopSerialPort();//关闭串口
    void startPollDivices();//开启设备轮询
    void stopPollDivcies();//停止设备轮询
    void sendCommand2Divice(int devicesID, const QByteArray& command); //手动发送指令信息给某个设备

signals:
    void sigdataReceive(int deviceID, const QByteArray& data);//来自设备的数据
    void sigserialIsOpen(QString);//串口已经打开消息
    void sigserialOpen(QString);//串口打开成功的消息
    void sigserialClose(QString);//串口关闭信号
    void sigerrorOccured(QString error);//错误信号

private:

    void pollDivcies();//轮询设备
    QByteArray creatModbusRequest(int deviceID, uint8_t functionCode, uint16_t startAddress, uint16_t registerCount);
    int responseTimeSet;//串口超时时间
    QTimer* pollingTime;
    QSerialPort* port;//串口实例对象
    QThread* subThread;   //创建的子线程
    QMutex mutex; //线程锁
    QWaitCondition waitCondition;//线程等待控制
    bool pollingActive;//是否继续轮询
    QQueue<QPair<int, QByteArray>> requestQueue; //设备指令队列
};

#endif // SERIALMANAGER_H





